<template>
	<div v-if="props.isPage" class="appointment-page">
		<div class="page-header">
			<h2>视训管理</h2>
			<el-button type="primary" @click="handlePrint">
				<el-icon><Printer /></el-icon>
				打印
			</el-button>
		</div>
		<!-- 页面模式的内容 -->
		<div class="page-content">
			<!-- 页面模式下隐藏选择框，显示固定信息 -->
			<div class="info-display">
				<template v-if="shopSelect === 1">
					<div class="info-item">
						<span class="label">门店：</span>
						<cl-select 
							class="appoint-item" 
							v-model="currentShopId" 
							:options="dict.get('Shop')" 
							prop="status"
							style="width: 200px;"
							@change="onShopChange"
						/>
					</div>
				</template>
				<template v-else>
					<div class="info-item">
						<span class="label">门店：</span>
						<span class="value">{{ shopName }}</span>
					</div>
				</template>
				<div class="info-item">
					<span class="label">日期：</span>
					<cl-date-picker
						v-model="startDate"
						type="valueFormat"
						prop="status"
						valueFormat="'YYYY-MM-DD'"
						placeholder="选择开始日期"
					/>
				</div>
			</div>
			<!-- 预约表格部分 -->
			<div class="appointment-table" v-if="currentShopId && currentDoctorId">
				<table>
					<thead>
						<tr>
							<th>时间</th>
							<th v-for="(date, index) in weekDates" :key="index">
								{{ getWeekDayText(date.weekDay) }}({{ date.dateStr }})
							</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="time in timeSlots" :key="time.value">
							<td class="time-column">{{ time.label }}</td>
							<td
								v-for="(day, index) in 7"
								:key="index"
								class="time-slot"
								:class="{
									available: time.availableSlots[index],
									unavailable: !time.availableSlots[index],
									selected: selectedTime === time.value && selectedDay === index,
									signed: time.appointmentInfo?.[index]?.appointmentStatus === 1, // 已经有了签到状态的样式绑定
									'can-sign':
										props.isPage &&
										time.appointments?.[index] &&
										time.appointmentInfo?.[index]?.appointmentStatus === 0,
									...(time.classStyles && time.classStyles[index]
										? { [time.classStyles[index]]: true }
										: {})
								}"
								:data-time="time.value"
								:data-weekday="weekDates[index].weekDay"
								@click="
									time.classIds[index] && time.classStyles && time.classStyles[index]
										? handleClassSelect(time.classIds[index], index)
										// : openStudentEditDialog(time, index)
										: createClass(time, index)
								"
							>
								<span
									v-if="time.appointments && time.appointments[index]"
									class="class-name"
								>
									{{ time.appointments[index] }}
								</span>
							</td>
						</tr>
					</tbody>
				</table>
			</div>
			<div v-else>
				<div style="padding: 10px; text-align: center">请联系管理员绑定店铺</div>
			</div>
		</div>
	</div>
	<el-dialog v-model="SignListVisible" :title="t('班级学员')" width="80%">
		<!--添加学员-->
		<el-button type="primary" @click="handleAddStudent">添加学员</el-button>
		<el-table :data="students" :border="true" style="width: 100%">
			<el-table-column prop="name" :label="t('学员姓名')" />
			<el-table-column prop="phone" :label="t('手机号')" />
			<el-table-column prop="buyCount" :label="t('购买次数')" />
			<el-table-column prop="remainCount" :label="t('剩余次数')" />
			<el-table-column prop="appointTime" :label="t('报名时间')" />
			<el-table-column prop="signStatusText" :label="t('签到状态')" />
			<el-table-column :label="t('操作')" width="200">
				<template #default="scope">
					<template v-if="scope.row.signStatus !== 1">
						<el-button type="primary" size="small" @click="handleSignIn(scope.row)">
							{{ t('签到') }}
						</el-button>
						<el-button type="danger" size="small" @click="handleQuit(scope.row)">
							{{ t('退班') }}
						</el-button>
					</template>
				</template>
			</el-table-column>
		</el-table>
	</el-dialog>
	<!-- 学员选择弹窗 -->
	<el-dialog v-model="studentSelectVisible" :title="t('选择学员')" width="80%">
		<cl-crud ref="Crud">
			<cl-row>
				<!-- 刷新按钮 -->
				<cl-refresh-btn />
				<!-- 新增按钮 -->
				<cl-add-btn />
				<!-- 删除按钮 -->
				<!-- <cl-multi-delete-btn /> -->
				<cl-export-btn :columns="Table?.columns" />
				<cl-flex1 />
				<!-- 条件搜索 -->
				<cl-search ref="Search" />
			</cl-row>
			<cl-row>
				<!-- 数据表格 -->
				<cl-table ref="Table">
					<!-- 插槽的渲染方式 #[component.name] -->
					<template #slot-appoint-btn="{ scope }">
						<el-button
							type="success"
							@click="
								() => {
									appointClass(scope.row);
								}
							"
							>预约</el-button
						>
					</template>
				</cl-table>
			</cl-row>

			<cl-row>
				<cl-flex1 />
				<!-- 分页控件 -->
				<cl-pagination />
			</cl-row>

			<!-- 新增、编辑 -->
			<cl-upsert ref="upsertRef" />
		</cl-crud>
	</el-dialog>
	<StudentEditDialog v-model="editDialogVisible" :student-id="selectedStudentId" />
</template>

<script lang="ts" setup>
import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { ref, watch, onMounted, nextTick } from 'vue';
import { useDict } from '/$/dict';
import { useCool } from '/@/cool';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Printer } from '@element-plus/icons-vue';
import { useBase } from '/$/base';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import StudentEditDialog from '../components/ShopStudentEdit.vue';

const { service } = useCool();
const { dict } = useDict();
const { t } = useI18n();
const route = useRoute();
const shopSelect = ref(parseInt(route.query.shopSelect as string) || 0);

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	},
	studentId: {
		type: Number,
		default: 0
	},
	isPage: {
		type: Boolean,
		default: true
	}
});

const emit = defineEmits(['update:modelValue', 'success']);

const visible = ref(false);
const currentDoctorId = ref('');
const currentShopId = ref('');
const selectedTime = ref('');
const startDate = ref(new Date().toISOString().split('T')[0]);
const doctorList = ref([]);
const timeSlots = ref([]);
const selectedDay = ref(-1);
const weekDates = ref([]);
// 添加新的响应式变量
const shopName = ref('');
const { user } = useBase();

// 学员列表弹窗控制
const SignListVisible = ref(false);
const loading = ref(false);
const students = ref([]);
const currentClassId = ref('');

// 添加响应式变量

const studentSelectVisible = ref(false);
const selectedClassId = ref('');
const Crud = useCrud({
  service: service.student.student.info
})

// cl-table
const Table = useTable({
	columns: [
		{ type: 'selection', hidden: true },
		{ label: t('姓名'), prop: 'name', minWidth: 140 },
		{ label: t('手机号'), prop: 'phone', minWidth: 140 },
		{
			label: t('性别'),
			prop: 'gender',
			minWidth: 60,
			formatter: (row, column, cellValue) => {
				const gender = options.gender.find(item => item.value === cellValue);
				return gender ? gender.label : cellValue;
			}
		},
		{
			label: t('生日'),
			prop: 'birthday',
			minWidth: 140,
			sortable: 'custom',
			component: {
				name: 'cl-date-text',
				props: { format: 'YYYY-MM-DD' }
			}
		},
		{
			label: t('来源'),
			prop: 'source',
			formatter: (row, column, cellValue) => {
				const source = dict.get('Source').value.find(item => item.value === cellValue);
				return source ? source.label : cellValue;
			}
		},
		{
			label: t('所属门店'),
			prop: 'shop',
			width: 100,
			formatter: (row, column, cellValue) => {
				const shop = dict.get('Shop').value.find(item => item.value === cellValue);
				return shop ? shop.label : cellValue;
			}
		},
		{ label: t('销售'), prop: 'salesName' },
		{
			label: t('项目'),
			prop: 'project',
			dict: dict.get('Project'),
			minWidth: 200
		},
		{
			label: t('入组'),
			prop: 'inGroup',
			formatter: (row, column, cellValue) => {
				const inGroup = dict.get('inGroup').value.find(item => item.value === cellValue);
				return inGroup ? inGroup.label : cellValue;
			},
			minWidth: 100
		},
		{ label: t('购买次数'), prop: 'buyCount', minWidth: 100 },
		{ label: t('剩余次数'), prop: 'remainCount', minWidth: 100 },
		{ label: t('备注'), prop: 'remark', showOverflowTooltip: true },
		{
			type: 'op',
			buttons: ['slot-appoint-btn', 'slot-edit-btn', 'slot-profile-btn'],
			width: 400
		}
	]
});

// cl-search
const Search = useSearch({
	items: [
		{
			prop: 'source',
			component: {
				name: 'cl-select',
				props: { options: dict.get('Source'), placeholder: '渠道' }
			}
		},
		{
			prop: 'project',
			component: {
				name: 'cl-select',
				props: {
					tree: true,
					checkStrictly: true,
					options: dict.get('Project'),
					placeholder: '项目'
				}
			}
		},
		{
			prop: 'inGroup',
			component: {
				name: 'cl-select',
				props: { options: dict.get('inGroup'), placeholder: '入组' }
			}
		},
		{
			prop: 'shopId',
			component: {
				name: 'cl-select',
				props: { options: dict.get('Shop'), placeholder: '门店' }
			}
		},
		{
			prop: 'phone',
			component: {
				name: 'el-input',
				props: { placeholder: '请输入电话' }
			}
		},
		{
			prop: 'name',
			component: {
				name: 'el-input',
				props: { placeholder: '请输入姓名' }
			}
		}
	]
});

// 在handleAddStudent方法中获取所有学员
async function handleAddStudent() {
  // 确保当前有选中的班级
  if (!currentClassId.value) {
    ElMessage.warning('请先选择班级');
    return;
  }
  selectedClassId.value = currentClassId.value;
  studentSelectVisible.value = true;
}

// 预约班级
async function appointClass() {
	console.log('appointClass')
}

// 监听组件挂载
onMounted(() => {
	if (props.isPage) {
		getCurrentUserInfo();
	}
});

watch(
	() => route.path,
	async newPath => {
		if (newPath.endsWith('zhongtaiShopAppoint')) {
			shopSelect.value = 1;
		} else {
			shopSelect.value = 0;
		}
	},
	{ immediate: true }
);

// 监听 modelValue 变化
watch(
	() => props.modelValue,
	val => {
		visible.value = val;
	}
);

// 监听 visible 变化
watch(
	() => visible.value,
	val => {
		emit('update:modelValue', val);
		if (!val) {
			resetForm();
		}
	}
);

// 监听选择变化
watch([startDate], ([newStartDate]) => {
	if (currentShopId.value && newStartDate) {
		calculateWeekDates(newStartDate);
		getAppointmentList();
	}
});

// 门店选择变化时重新获取数据
const onShopChange = () => {
	if (currentShopId.value && startDate.value) {
		calculateWeekDates(startDate.value);
		getAppointmentList();
	}
};

// 修改获取当前用户信息的函数
async function getCurrentUserInfo() {
	if (props.isPage) {
		if (shopSelect.value !== 1) {
			currentShopId.value = user.info?.shop;
			currentDoctorId.value = 1;
			// 获取店铺名称
			const shopList = dict.get('Shop').value;
			const shop = shopList.find(s => s.value === currentShopId.value);
			if (shop) {
				shopName.value = shop.label;
			}
		} else {
			currentShopId.value = 126;
			currentDoctorId.value = 1;
		}

		// 自动获取预约列表
		calculateWeekDates(startDate.value);
		getAppointmentList();
	}
}

// 计算一周的日期
function calculateWeekDates(startDateStr: string) {
	const dates = [];
	const start = new Date(startDateStr);

	for (let i = 0; i < 7; i++) {
		const date = new Date(start);
		date.setDate(date.getDate() + i);
		dates.push({
			weekDay: date.getDay(),
			dateStr: `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
		});
	}

	weekDates.value = dates;
}

// 获取星期几的文字
function getWeekDayText(day: number): string {
	const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	return weekDays[day];
}


function generateTimeSlots(startTime: string, endTime: string) {
	const slots = [];
	// 根据weekDates生成开始和结束时间的日期
	const start = new Date(`2000/01/01 ${startTime}`);
	const end = new Date(`2000/01/01 ${endTime}`);

	while (start <= end) {
		const hours = start.getHours().toString().padStart(2, '0');
		const minutes = start.getMinutes().toString().padStart(2, '0');
		const timeStr = `${hours}:${minutes}`;
		const availableSlots = new Array(7).fill(true);
		

		slots.push({
			label: timeStr,
			value: timeStr,
			availableSlots: availableSlots,
			appointments: new Array(7).fill(null)
		});

		start.setMinutes(start.getMinutes() + 60);
	}
	return slots;
}   

async function getAppointmentList() {
	const startDateStr = new Date(startDate.value).toISOString().split('T')[0];
	const endDate = new Date(startDate.value);
	endDate.setDate(endDate.getDate() + 7);
	const endDateStr = endDate.toISOString().split('T')[0];

	const params = {
		date: startDateStr,
		endDate: endDateStr,
		shopId: currentShopId.value,
		doctorId: currentDoctorId.value
	};

	try {
		const resClass = await service.appointment.info.dateClass(params);
		// 初始化时间槽
		timeSlots.value = generateTimeSlots('09:00', '19:30');
		// 处理课程占位，不依赖于 resAppoint 的存在
		if (resClass) {
			resClass.forEach(classItem => {
				const startDateTime = new Date(classItem.startTime);
				const endDateTime = new Date(classItem.endTime);
				// 获取开始和结束时间的小时和分钟
				const startHour = startDateTime.getHours();
				const startMinute = startDateTime.getMinutes();
				const endHour = endDateTime.getHours();
				const endMinute = endDateTime.getMinutes();

				// 计算日期在当前周的哪一天
				const classDate = startDateTime.toISOString().split('T')[0];
				const dayIndex = weekDates.value.findIndex(date => {
					const classMonth = classDate.substring(5, 7);
					const classDay = classDate.substring(8, 10);
					return date.dateStr === `${classMonth}-${classDay}`;
				});

				if (dayIndex !== -1) {
					let isFirstSlot = true;
					let slotCount = 0;
					// 计算总时间槽数
					const totalSlots = Math.ceil(
						(endDateTime.getTime() - startDateTime.getTime()) / (30 * 60 * 1000)
					);

					// 遍历时间段，标记课程占用的时间槽
					timeSlots.value.forEach(slot => {
						const [slotHour, slotMinute] = slot.value.split(':').map(Number);
						const slotTime = slotHour * 60 + slotMinute;
						const startTime = startHour * 60 + startMinute;
						const endTime = endHour * 60 + endMinute;
						// 当日期一致，上下课时间一致，则赋值
						if (slotTime >= startTime && slotTime < endTime) {
							// 判断班级是否可以预约（人数未满）
							const isClassAvailable = classItem.currentCount < classItem.limitCount;
							slot.availableSlots[dayIndex] = isClassAvailable;
							if (!slot.classStyles) slot.classStyles = {};
                            // 初始化classIds对象（如果不存在）
                            if (!slot.classIds) slot.classIds = {};
                            // 按日期存储classId
                            slot.classIds[dayIndex] = classItem.id; // 添加课程ID
							// 当日期也一致的时候才赋值id
							slot.classId = classItem.id; // 添加课程ID
							console.log('classId', slot.classId, classItem.id)
							

							if (isFirstSlot) {
								// 修改这里，添加人数显示
								slot.appointments[dayIndex] =
									`${classItem.className}(${classItem.currentCount}/${classItem.limitCount})`;
								slot.classStyles[dayIndex] =
									`class-block first ${isClassAvailable ? 'available' : 'unavailable'}`;
								isFirstSlot = false;
							} else if (slotCount < totalSlots - 1) {
								slot.appointments[dayIndex] = '';
								slot.classStyles[dayIndex] =
									`class-block middle ${isClassAvailable ? 'available' : 'unavailable'}`;
							} else {
								slot.appointments[dayIndex] = '';
								slot.classStyles[dayIndex] =
									`class-block last ${isClassAvailable ? 'available' : 'unavailable'}`;
							}
							slotCount++;
						}
					});
				}
			});
		}
	} catch (error) {
		console.log('获取预约信息失败', error);
		ElMessage.error('获取预约信息失败');
	}
}

// 修改时间选择处理函数
function handleTimeSelect(time, dayIndex) {
	if (time.availableSlots[dayIndex]) {
		if (selectedTime.value === time.value && selectedDay.value === dayIndex) {
			selectedTime.value = '';
			selectedDay.value = -1;
		} else {
			selectedTime.value = time.value;
			selectedDay.value = dayIndex;
		}
	}
}

// 添加班级预约处理函数
async function handleClassSelect(classId: number, index: number) {
	console.log('handleClassSelect', classId, index, timeSlots.value[index]);
	if (props.isPage) {
		console.log('handleClassSelect', classId);
		// 页面模式下，触发查看班级事件
		viewStudents({ id: classId });
		return;
	}
	try {
		// 使用 Element Plus 的确认弹窗
		await ElMessageBox.confirm('是否确认预约该班级？', '预约确认', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		});

		// 用户确认后继续预约流程
		await service.class.classAppoint.appointClass({
			studentId: props.studentId,
			classId: classId
		});
		ElMessage.success('班级预约成功');
		visible.value = false;
		emit('success');
	} catch (error: any) {
		// 如果是用户取消，不显示错误提示
		if (error !== 'cancel') {
			ElMessage.error(error?.message || '班级预约失败');
		}
	}
}

// 修改预约确认函数
async function handleConfirmAppointment() {
	if (!selectedTime.value || selectedDay.value === -1) {
		ElMessage.warning('请选择预约时间');
		return;
	}

	// 使用选中日期对应的完整日期
	const selectedDateInfo = weekDates.value[selectedDay.value];
	if (!selectedDateInfo) {
		ElMessage.warning('日期选择有误');
		return;
	}

	// 从当前选中的日期信息构建完整日期
	const [month, day] = selectedDateInfo.dateStr.split('-');
	const currentYear = new Date().getFullYear();
	const dateStr = `${currentYear}-${month}-${day}`;

	const params = {
		studentId: props.studentId,
		date: dateStr,
		shopId: currentShopId.value,
		doctorId: currentDoctorId.value,
		time: selectedTime.value
	};

	try {
		await service.appointment.info.appoint(params);
		ElMessage.success('预约成功');
		visible.value = false;
		emit('success');
	} catch (error: any) {
		ElMessage.error(error.message || '预约失败');
	}
}

// 重置表单
function resetForm() {
	currentDoctorId.value = '';
	currentShopId.value = '';
	selectedTime.value = '';
	startDate.value = new Date().toISOString().split('T')[0];
	timeSlots.value = [];
}
function handlePrint() {
	// 确保内容已加载
	nextTick(() => {
		const printContent = document.querySelector('.appointment-table');
		if (printContent) {
			const originalContents = document.body.innerHTML;
			const printStyles = `
                <style>
                    @page {
						size: landscape;
						margin: 1cm;  /* 增加页面边距 */
					}
					.print-container {
						margin-bottom: 20px;
						text-align: center;
						padding: 0 2cm;  /* 添加左右内边距 */
					}
					.print-container table {
						width: 90%;  /* 调整表格宽度，不要占满整个页面 */
						border-collapse: collapse;
						border: 1px solid black;
						font-size: 14px;
						margin: auto;  /* 保持表格居中 */
					}
					.print-header {
						text-align: center;
						margin-bottom: 10px;
						display: inline-flex;  /* 改为 inline-flex */
						align-items: center;
						gap: 10px;  /* logo 和标题之间的间距 */
					}
					.print-logo {
						height: 30px;
						width: auto;
					}
					.print-title {
						font-weight: bold;
					}
                    /* 表格基础样式 */
                    .appointment-table table {
                        width: 100%;
                        border-collapse: collapse;
                        border: 1px solid black;
                    }
                    .appointment-table th,
                    .appointment-table td {
                        border: 1px solid black;
                        text-align: center;
                    }
                    /* 时间槽样式 */
                    .appointment-table .time-slot {
                        min-height: unset;
                        overflow: hidden;
                    }
                    .appointment-table .time-slot.available {
                        background-color: #333;
                    }
                    .appointment-table .time-slot.unavailable {
                        background-color: #eee;
                    }
                    /* 班级名称样式 */
                    .appointment-table .class-name {
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        max-width: 100%;
                        display: block;
                    }
                    /* 表头样式 */
                    .appointment-table thead th {
                        font-weight: normal;
                        white-space: nowrap;
                    }
                    /* 时间列样式 */
                    .appointment-table .time-column {
                        width: 8%;
                        background-color: #f5f7fa;
                    }
                </style>
                <div class="print-container">
					<div class="print-header">
						<img class="print-logo" src="https://joyballet.oss-cn-beijing.aliyuncs.com/eyemanager/logo/logo.png" alt="Logo">
						<div class="print-title">${shopName.value}预约名单-${startDate.value}</div>
					</div>
					${printContent.innerHTML}
				</div>
            `;
			document.body.innerHTML = printStyles;
			// 等待图片加载完成后再打印
			const logoImg = document.querySelector('.print-logo');
			if (logoImg) {
				logoImg.onload = () => {
					window.print();
					document.body.innerHTML = originalContents;
					location.reload();
				};

				// 添加错误处理
				logoImg.onerror = () => {
					console.error('Logo 加载失败');
					window.print();
					document.body.innerHTML = originalContents;
					location.reload();
				};
			} else {
				window.print();
				document.body.innerHTML = originalContents;
				location.reload();
			}
			// document.body.innerHTML = originalContents;
			// 重新挂载Vue应用
			// location.reload();
		}
	});
}

// 查看学员方法
async function viewStudents(row: any) {
	currentClassId.value = row.id;
	SignListVisible.value = true;
	loading.value = true;

	try {
		const res = await service.class.classAppoint.getClassStudents({
			classId: row.id
		});
		students.value = res;
		console.log('viewStudents', res, students);
	} catch (err) {
		ElMessage.error(t('获取学员列表失败'));
	} finally {
		loading.value = false;
	}
}
// 签到方法
async function handleSignIn(row: any) {
	try {
		// 添加确认弹窗
		await ElMessageBox.confirm(t('确认要为该学员签到吗？'), t('签到确认'), {
			confirmButtonText: t('确认'),
			cancelButtonText: t('取消'),
			type: 'info'
		});

		// 用户确认后继续签到流程
		await service.class.classAppoint.signIn({
			appointId: row.appointId
		});
		ElMessage.success(t('签到成功'));
		viewStudents({ id: currentClassId.value });
	} catch (err: any) {
		// 如果是用户取消操作，不显示错误提示
		if (err !== 'cancel') {
			ElMessage.error(err.message || t('签到失败'));
		}
	}
}

// 退班方法
async function handleQuit(row: any) {
	ElMessageBox.confirm(t('确认要将该学员退班吗？'), t('提示'), {
		type: 'warning'
	})
		.then(async () => {
			try {
				await service.class.classAppoint.cancelAppoint({
					id: row.appointId
				});
				ElMessage.success(t('退班成功'));
				viewStudents({ id: currentClassId.value });
			} catch (err: any) {
				ElMessage.error(err.message || t('退班失败'));
			}
		})
		.catch(() => {});
}

// 已到店
async function appointCome(id: number) {
	try {
		// 添加确认弹窗
		await ElMessageBox.confirm(t('确认要为该学员签到吗？'), t('签到确认'), {
			confirmButtonText: t('确认'),
			cancelButtonText: t('取消'),
			type: 'info'
		});

		// 用户确认后继续签到流程
		await Crud.value?.service.appointCome({ appointId: id });
		ElMessage.success('签到成功');
		// 刷新表格数据
		Crud.value?.refresh();
	} catch (err: any) {
		// 如果是用户取消操作，不显示错误提示
		if (err !== 'cancel') {
			ElMessage.error(err.message || '签到失败');
		}
	}
}
// 点击空白地方，新建班级，并且显示班级
async function createClass(time, index) {
    console.log('createClass', time, index);
}

async function handleTimeClick(time, index) {
	if (props.isPage && time.appointments?.[index] && time.appointmentInfo?.[index]) {
		// 在页面模式下，如果是未签到的预约，执行签到
		if (time.appointmentInfo[index].appointmentStatus === 0) {
			try {
				await ElMessageBox.confirm('是否确认签到？', '签到确认', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'info'
				});

				await service.appointment.info.appointCome({
					appointId: time.appointmentInfo[index].id
				});
				ElMessage.success('签到成功');
				// 更新签到状态
				time.appointmentInfo[index].appointmentStatus = 1;
				// 刷新预约列表
				getAppointmentList();
			} catch (error: any) {
				if (error !== 'cancel') {
					ElMessage.error(error?.message || '签到失败');
				}
			}
		} else if (time.appointmentInfo[index].appointmentStatus === 1) {
			try {
				await ElMessageBox.confirm('是否取消签到？', '取消确认', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'info'
				});

				await service.appointment.info.appointCome({
					appointId: time.appointmentInfo[index].id
				});
				ElMessage.success('取消签到成功');
				// 更新签到状态
				time.appointmentInfo[index].appointmentStatus = 1;
				// 刷新预约列表
				getAppointmentList();
			} catch (error: any) {
				if (error !== 'cancel') {
					ElMessage.error(error?.message || '取消签到失败');
				}
			}
		}
		return;
	}

	// 原有的时间选择逻辑
	if (time.classId && time.classStyles && time.classStyles[index]) {
		handleClassSelect(time.classId);
	} else {
		handleTimeSelect(time, index);
	}
}
</script>

<style scoped>
.time-slot.signed {
	background-color: #71b84e !important;
	color: #fff !important;
}

.time-slot.can-sign {
	cursor: pointer;
	position: relative;
}

.time-slot.can-sign:hover {
	background-color: #95d475;
	color: white;
}
.appoint-item {
	margin-top: 5px;
	margin-bottom: 20px;
}

.timeList {
	margin-top: 20px;
}

.time-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}

.time-slot {
	width: 45%;
	text-align: center;
	border-radius: 4px;
	cursor: pointer;
	background-color: #fff;
	border: 1px solid #dcdfe6;
}

.time-slot.available {
	background-color: #e1f3d8;
	color: #67c23a;
}

.time-slot.unavailable {
	background-color: #fde2e2;
}

/* 工作日早上时间段的特殊样式 - 确保优先级高于普通的 unavailable 样式 */
td[data-weekday='1'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='2'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='3'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='4'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='5'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='1'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='2'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='3'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='4'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='5'].time-slot.unavailable[data-time='09:30'] {
	background-color: #f5f7fa !important; /* 使用灰色背景 */
	color: #909399 !important; /* 使用灰色文字 */
}
.time-slot.selected {
	background-color: #fff;
	border: 1px solid #409eff;
	color: #409eff;
}
.appointment-table {
	margin-top: 20px;
	overflow-x: auto;
	margin-bottom: 20px; /* 添加底部间距 */
}

table {
	width: 100%;
	table-layout: fixed; /* 添加这行确保列等宽 */
	border-collapse: collapse;
	border: 1px solid #dcdfe6;
}

th,
td {
	border: 1px solid #dcdfe6;
	padding: 15px;
	text-align: center;
	width: 12.5%; /* 设置每列宽度为相等的比例（100% / 8列） */
	overflow: hidden; /* 防止内容溢出 */
	text-overflow: ellipsis; /* 内容溢出时显示省略号 */
	white-space: nowrap; /* 防止内容换行 */
}

.time-column {
	background-color: #f5f7fa;
	font-weight: bold;
	width: 12.5%; /* 修改为与其他列相同的宽度 */
}

.time-slot {
	cursor: pointer;
	/* height: 40px; */
	transition: all 0.3s;
}

.time-slot.available {
	background-color: #e1f3d8;
	color: #67c23a;
}

.time-slot.unavailable {
	/* background-color: #fde2e2; */
	color: #f56c6c;
	/* cursor: not-allowed; */
}

.time-slot.selected {
	background-color: #fff;
	border: 2px solid #409eff;
	color: #409eff;
}

/* 修改课程占位的特殊样式 */
.time-slot.class-block {
	position: relative;
	cursor: not-allowed;
	border: 1px solid #dcdfe6;
}

.time-slot.class-block.available {
	background-color: #fff7e6; /* 柔和的黄色背景 */
	color: #e6a23c; /* 暖橙色文字，与黄色背景搭配 */
	cursor: pointer;
}

.time-slot.class-block.unavailable {
	background-color: #fde2e2;
	color: #f56c6c;
}

.time-slot.class-block.first {
	border-bottom: none;
	border-radius: 4px 4px 0 0;
}

.time-slot.class-block.middle {
	border-top: none;
	border-bottom: none;
	color: transparent;
}

.time-slot.class-block.last {
	border-top: none;
	border-radius: 0 0 4px 4px;
}

.time-slot.class-clickable {
	cursor: pointer !important;
}

.time-slot.class-block {
	position: relative;
	background-color: #fde2e2;
	color: #f56c6c;
	cursor: not-allowed;
	border: 1px solid #dcdfe6;
}

.time-slot.class-block .class-name {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 1;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: 90%;
}

/* 半格样式 */
.time-slot.half-slot {
	background: linear-gradient(to bottom, #fde2e2 50%, transparent 50%) !important;
	color: #f56c6c;
}

/* 添加页面模式的样式 */
.appointment-page {
	padding: 20px;
	background: #fff;
	min-height: 100vh; /* 设置最小高度为视口高度 */
	display: flex;
	flex-direction: column;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
}

.page-content {
	max-width: 1200px;
	margin: 0 auto;
	flex: 1;
	overflow-y: auto; /* 添加垂直滚动 */
	padding-bottom: 60px; /* 底部预留空间 */
}

.form-group {
	margin-bottom: 20px;
}

.page-footer {
	margin-top: 20px;
	text-align: right;
}

/* 添加信息显示样式 */
.info-display {
	margin-bottom: 20px;
	padding: 15px;
	background-color: #f5f7fa;
	border-radius: 4px;
}

.info-item {
	margin-bottom: 10px;
	display: flex;
	align-items: center;
}

.info-item:last-child {
	margin-bottom: 0;
}

.info-item .label {
	font-weight: bold;
	margin-right: 10px;
	min-width: 60px;
}

.info-item .value {
	color: #606266;
}
</style>
